﻿using MiniJob.Service;

namespace MiniJob.Orleans;

public interface IScheduleGrain : IGrainWithIntegerKey
{
    Task StartAsync();
}

public class ScheduleGrain : GrainBase, IScheduleGrain, IRemindable
{
    public static string ScheduleReminderName = "ScheduleReminderName";

    public override async Task OnActivateAsync(CancellationToken cancellationToken)
    {
        _ = await this.RegisterOrUpdateReminder(ScheduleReminderName, TimeSpan.FromSeconds(3), TimeSpan.FromMinutes(1));
    }

    public async Task ReceiveReminder(string reminderName, TickStatus status)
    {
        await StartAsync();
    }

    public async Task StartAsync()
    {
        try
        {
            var appService = ServiceProvider.GetRequiredService<IAppService>();
            var apps = await appService.AllAsync();
            if (apps.Count == 0)
            {
                Logger.LogInformation("current server has no app's job to schedule.");
                return;
            }
            foreach (var app in apps)
            {
                await GrainFactory.GetGrain<IAppGrain>(app.Id)
                    .ScheduleAppAsync();
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "schedule normal job failed.");
        }
    }
}
